use dataset_county, clear

keep if year >= 1972
drop if mi(statea) | mi(pctcollege) | mi(demvoteshare)

egen sdpctcollege = sd(pctcollege), by(year)
egen minpctcollege = min(pctcollege), by(year statea)
egen maxpctcollege = max(pctcollege), by(year statea)
replace pctcollege = (pctcollege - minpctcollege) / (maxpctcollege - minpctcollege)

gen y = demvoteshare

su pctcollege if year == 2016 [aw=pop], det
 
gen B = .
gen A = .
gen Bstate = .
gen Astate = .
levelsof year, local(levels)
foreach l of local levels {
	reg y pctcollege if year == `l' [aw=pop]
	replace B = _b[pctcollege] if year == `l'
	replace A = _b[_cons] if year == `l'
}
keep if key == 1

levelsof statea, local(states)
levelsof year, local(levels)
foreach s of local states {
	foreach l of local levels {
		reg y pctcollege if year == `l' & statea == "`s'" [aw=pop]
		replace Bstate = _b[pctcollege] if year == `l' & statea == "`s'"
		replace Astate = _b[_cons] if year == `l' & statea == "`s'"
	}
}

collapse B A Bstate Astate, by(year statea)
replace B = B+A
replace Bs = Bs+As

#delimit;

gr tw
	(con A year if statea == "IA", col(black))
	(con B year if statea == "IA", col(gray) msym(s))
	,
		legend(off)
		yline(50, lpat(dash))
		plotregion(style(none))
		xlab(1972(4)2016)
		ylab(, angle(horiz))
		text(65 2008 "High education", col(gray))
		text(40 2000 "Low education")
		xtitle("Year")
		ytitle("Democratic vote %")
		;

#delimit cr

gr export "figure 5a.pdf", replace

local j = 1
levelsof statea, local(levels)
foreach l of local levels {

	di "`l'"
	
	local text1 text(67 2004 "High education", col(gray))
	local text2 text(40 2000 "Low education")
	if `j' > 1 local text1
	if `j' > 1 local text2
		
	#delimit;

	gr tw 
		(con As Bs year if statea == "`l'", col(black gray) msym(O s))
		,
			subtitle(, fcol(none) lwid(none))
			plotregion(style(none))
			yline(50, lpat(dash))
			ylab(, angle(horiz) nogrid)
			xlab(1972(4)2016, angle(45) labsize(small))
			xtitle("")
			legend(off)
			name(g`j', replace)
			title(`l')
			;
			
	#delimit cr
	
	local j = `j' + 1

}

gr combine g1 g2 g3 g4 g5, imargin(zero) l1title("Democratic vote %") ///
	b1title("Year")
	
gr export "figure 5b.pdf", replace
